package whu.edu.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;
import whu.edu.demo.domain.Users;
import whu.edu.demo.util.JwtTokenUtil;


@RestController
@CrossOrigin
@RequestMapping("/au")
public class AuthenticationController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;


    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody Users user){
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        try{
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword())
            );
            final UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
            final String token = jwtTokenUtil.generateToken(userDetails);
            return ResponseEntity.ok(token);
        }catch(Exception e){
            return ResponseEntity.badRequest().body("用户认证失败");
        }
    }


}